package com.circus.trace.controller.transport;

import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.circus.trace.bean.material.transport.Transport;
import com.circus.trace.biz.material.transport.TransportService;
import com.circus.trace.controller.BaseController;
import com.circus.trace.ext.shiro.anno.SINORequiresPermissions;
import com.circus.trace.vo.InstallPermission;

import club.zhcs.common.Result;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("transport")
public class TransportController extends BaseController {

	@Autowired
	TransportService transportService;

	@GetMapping("list")
	@SINORequiresPermissions(InstallPermission.TRANSPORT_LIST)
	@ApiOperation(value = "进出口分页列表")
	public Result list(@RequestParam(value = "page", defaultValue = "1") @ApiParam("页码") int page) {
		return Result.success().addData("pager", transportService.searchByPage(fixPage(page), Cnd.where("enabled", "=", true).desc("id")));
	}

	@GetMapping("search")
	@SINORequiresPermissions(InstallPermission.TRANSPORT_LIST)
	@ApiOperation(value = "进出口分页检索")
	public Result search(@RequestParam("key") @ApiParam("搜索关键字") String key, @RequestParam(value = "page", defaultValue = "1") @ApiParam("页码") int page) {
		return Result.success()
				.addData("pager", transportService.searchByKeyAndPage(
						fixSearchKey(key),
						fixPage(page),
						Cnd.where("enabled", "=", true),
						"poe", "poi")
						.addParam("key", key));
	}

	@PostMapping(value = "add")
	@SINORequiresPermissions(InstallPermission.TRANSPORT_ADD)
	@ApiOperation(value = "新增进出口")
	public Result save(@RequestBody Transport transport) {
		return transportService.save(transport) == null ? Result.fail("保存进出口信息失败!") : Result.success().addData("transport", transport);
	}

	@PostMapping(value = "edit")
	@SINORequiresPermissions(InstallPermission.TRANSPORT_EDIT)
	public Result edit(@RequestBody Transport transport) {
		return transportService.update(transport) == 1 ? Result.success() : Result.fail("更新进出口信息失败!");
	}
	
	/**
	 * 删除进出口
	 * 
	 * @param id
	 *            进出口id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@SINORequiresPermissions(value = { InstallPermission.AREA_DELETE })
	@ApiOperation("删除进出口")
	public Result delete(@PathVariable("id") @ApiParam("进出口id") long id) {
		return transportService.update(Chain.make("enabled", false), Cnd.where("id", "=", id)) == 1 ? Result.success() : Result.fail("删除进出口失败!");
	}
}
